<?php

class JWTUtils
{
    private static $secretKey = 'aini1314'; // 替换为你的密钥

    /**
     * 生成 JWT
     * @param array $payload 载荷数据
     * @param int $exp 有效期（秒）
     * @return string
     */
    public static function generateToken(array $payload, int $exp = 3600): string
    {
        $header = json_encode(['alg' => 'HS256', 'typ' => 'JWT']);
        $payload['exp'] = time() + $exp;

        $headerBase64 = self::base64UrlEncode($header);
        $payloadBase64 = self::base64UrlEncode(json_encode($payload));

        $signature = self::sign("$headerBase64.$payloadBase64", self::$secretKey);
        $token = "$headerBase64.$payloadBase64.$signature";
        global $rootPath;

        return $token;
    }


    /**
     * 验证 JWT
     * @param string $token
     * @return bool|string
     */
    public static function validateToken(string $token)
    {
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            return false;
        }

        [$headerBase64, $payloadBase64, $signature] = $parts;

        // 验证签名
        $validSignature = self::sign("$headerBase64.$payloadBase64", self::$secretKey);
        if (!hash_equals($validSignature, $signature)) {
            return false;
        }

        // 验证有效期
        $payload = json_decode(self::base64UrlDecode($payloadBase64), true);
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            return false;
        }

        return $payload;
    }

    /**
     * 解码 JWT
     * @param string $token
     * @return array|null
     */
    public static function decodeToken(string $token): ?array
    {
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            return null;
        }

        $payloadBase64 = $parts[1];
        return json_decode(self::base64UrlDecode($payloadBase64), true);
    }

    /**
     * 生成签名
     * @param string $data
     * @param string $key
     * @return string
     */
    private static function sign(string $data, string $key): string
    {
        return self::base64UrlEncode(hash_hmac('sha256', $data, $key, true));
    }

    /**
     * Base64 URL 编码
     * @param string $data
     * @return string
     */
    private static function base64UrlEncode(string $data): string
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    /**
     * Base64 URL 解码
     * @param string $data
     * @return string
     */
    private static function base64UrlDecode(string $data): string
    {
        return base64_decode(strtr($data, '-_', '+/'));
    }
}
/*
// 生成 Token
$payload = ['user_id' => 123, 'role' => 'admin','time'=>DateHelper::now()];
$token = JWTUtils::generateToken($payload, 3600);
echo "生成的 Token: $token\n";

// 验证 Token
$isValid = JWTUtils::validateToken($token);
if ($isValid) {
    echo "Token 有效，数据: " . json_encode($isValid) . "\n";
} else {
    echo "Token 无效\n";
}

// 解码 Token
$decoded = JWTUtils::decodeToken($token);
echo "解码的 Token 数据: " . json_encode($decoded) . "\n";*/